package com.fish.yssb.ui.page.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.fish.yssb.Consts;
import com.fish.yssb.R;
import com.fish.yssb.api.retData;
import com.fish.yssb.api.setApi;
import com.fish.yssb.app.BaseApp;
import com.fish.yssb.data.model.LoginUser;
import com.fish.yssb.data.model.TopRK;
import com.fish.yssb.ui.page.activity.AccountLoginActivity;
import com.fish.yssb.ui.page.activity.base.TmpActivity;
import com.fish.yssb.ui.page.activity.other.LogActivity;
import com.fish.yssb.ui.page.activity.other.ReadMQActivity;
import com.fish.yssb.ui.page.activity.other.RestActivity;
import com.fish.yssb.ui.page.activity.other.SafeActivity;
import com.fish.yssb.ui.page.activity.other.SyncTimeActivity;
import com.fish.yssb.ui.page.activity.other.UserManageActivity;
import com.fish.yssb.ui.page.activity.setPara.SetParaListActivity;
import com.fish.yssb.ui.page.adapter.AppAdapter;
import com.fish.yssb.ui.page.dialog.PublicNoticeDialog;
import com.fish.yssb.ui.page.dialog.ShowSQInfoDialog;
import com.fish.yssb.ui.page.util.LcndUtil;
import com.fish.yssb.ui.page.util.TopToastUtil;
import com.fish.yssb.ui.page.widget.HorizontalPageLayoutManager;
import com.fish.yssb.ui.page.widget.PagingItemDecoration;
import com.fish.yssb.ui.page.widget.PagingScrollHelper;
import com.hy.srv101.Dim2Data;
import com.hy.srv101.DimXLib;
import com.hy.srv101.IDimFace;
import com.jaeger.library.StatusBarUtil;
import com.syd.oden.circleprogressdialog.core.CircleProgressDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

import static android.app.Activity.RESULT_OK;


/**
 * Created by caobotao on 16/1/4.
 */
public class MainFragment extends BaseFragment implements View.OnClickListener, PagingScrollHelper.onPageChangeListener {

    private ViewGroup mMoreLayout;
    private List<ImageView> views = new ArrayList<ImageView>();

    private TimePickerView pvTime;

     private CircleProgressDialog circleProgressDialog
             ;

    private static boolean frist = true;
    private View mView;
    private LinearLayout  ll_top1,ll_top2,ll_top3,ll_top4,ll_r_area1,ll_r_area2,ll_r_area3,ll_r_area4,ll_r_area5,ll_r_area6;
    private ImageView im_icon1,im_icon2,im_icon3,im_icon4;
    private ScrollView sv_list;

    private LinearLayout ll_left1,ll_left2,ll_left3,ll_left4,ll_left5,ll_left6;
//    private String[] imageUrls = {};

    private ArrayList<String> imageUrls = new ArrayList<String>();
    private ArrayList<String> showUrls = new ArrayList<String>();
    private LinearLayout noticeLayout;
    private TextView tv_name,tv_login;
    private ImageView closeNotice;

    //首页顶部应用
    AppAdapter topAppAdapter;
    RecyclerView recyclerView;
    PagingScrollHelper scrollHelper = new PagingScrollHelper();


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_tab_main, container, false);

        }
        final LoginUser user = BaseApp.getInstance().user;
        initIconNew(mView);
        ll_top1 = mView.findViewById(R.id.ll_top1);
        ll_top2 = mView.findViewById(R.id.ll_top2);
        ll_top3 = mView.findViewById(R.id.ll_top3);
        ll_top4 = mView.findViewById(R.id.ll_top4);

        ll_r_area1 = mView.findViewById(R.id.ll_r_area1);
        ll_r_area2 = mView.findViewById(R.id.ll_r_area2);
        ll_r_area3 = mView.findViewById(R.id.ll_r_area3);
        ll_r_area4 = mView.findViewById(R.id.ll_r_area4);
        ll_r_area5 = mView.findViewById(R.id.ll_r_area5);
        ll_r_area6 = mView.findViewById(R.id.ll_r_area6);

        im_icon1 = mView.findViewById(R.id.im_icon1);
        im_icon2 = mView.findViewById(R.id.im_icon2);
        im_icon3 = mView.findViewById(R.id.im_icon3);
        im_icon4 = mView.findViewById(R.id.im_icon4);
        tv_login = mView.findViewById(R.id.tv_login);
        tv_name  = mView.findViewById(R.id.tv_name);
        sv_list = mView.findViewById(R.id.sv_list);

        ll_left1 = mView.findViewById(R.id.ll_left1);
        ll_left2 = mView.findViewById(R.id.ll_left2);
        ll_left3 = mView.findViewById(R.id.ll_left3);
        ll_left4 = mView.findViewById(R.id.ll_left4);
        ll_left5 = mView.findViewById(R.id.ll_left5);
        ll_left6 = mView.findViewById(R.id.ll_left6);

        ll_left1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setChangeLL(1);
            }
        });

        ll_left2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setChangeLL(2);
            }
        });

        ll_left3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setChangeLL(3);
            }
        });
        ll_left4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setChangeLL(4);
            }
        });

        ll_left5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setChangeLL(5);
            }
        });

        ll_left6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setChangeLL(6);
            }
        });

        ll_top2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!"".equalsIgnoreCase(user.getUserName()))
                {
                    SafeActivity.start(getActivity());

                }

            }
        });


        mView.findViewById(R.id.tv_bt2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if("".equalsIgnoreCase(user.getUserName())) {
                    noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String sendStatus = "";
                            if (view.getId() == R.id.btn_chancel_notice) {//暂存

                                noticeDialog.dismiss();
                            } else {//生成

                                noticeDialog.dismiss();

                            }
                            noticeDialog.dismiss();

                        }
                    }, 4, "", "用户未登录，无权限查看信息", "取消", "确定");
                    noticeDialog.show();
                }else{
                        LogActivity.start(getActivity());
                }


            }
        });

        mView.findViewById(R.id.tv_bt3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if("".equalsIgnoreCase(user.getUserName())) {
                    noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String sendStatus = "";
                            if (view.getId() == R.id.btn_chancel_notice) {//暂存

                                noticeDialog.dismiss();
                            } else {//生成

                                noticeDialog.dismiss();

                            }
                            noticeDialog.dismiss();

                        }
                    }, 4, "", "用户未登录，无权限查看信息", "取消", "确定");
                    noticeDialog.show();
                }else{
                        UserManageActivity.start(getActivity());
                }


            }
        });

        mView.findViewById(R.id.im_icon2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!"".equalsIgnoreCase(user.getUserName()))
                {
                    SafeActivity.start(getActivity());

                }
            }
        });
        mView.findViewById(R.id.im_icon3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readSQInfo(v);
            }
        });
        mView.findViewById(R.id.im_icon4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TmpActivity.start(getActivity());
            }
        });

        mView.findViewById(R.id.im_icon21).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TmpActivity.start(getActivity());
            }
        });

        mView.findViewById(R.id.im_icon31).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TmpActivity.start(getActivity());
            }
        });

        mView.findViewById(R.id.im_icon41).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TmpActivity.start(getActivity());
            }
        });

        mView.findViewById(R.id.im_icon51).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TmpActivity.start(getActivity());
            }
        });

        mView.findViewById(R.id.im_icon11).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TmpActivity.start(getActivity());
            }
        });

        mView.findViewById(R.id.im_icon12).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TmpActivity.start(getActivity());
            }
        });

        mView.findViewById(R.id.im_icon13).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TmpActivity.start(getActivity());
            }
        });

        mView.findViewById(R.id.im_icon14).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TmpActivity.start(getActivity());
            }
        });

        mView.findViewById(R.id.im_icon15).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TmpActivity.start(getActivity());
            }
        });

        mView.findViewById(R.id.im_icon16).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TmpActivity.start(getActivity());
            }
        });



        ll_top3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!"".equalsIgnoreCase(user.getUserName())) {
                    noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String sendStatus = "";
                            if (view.getId() == R.id.btn_chancel_notice) {//暂存

                                noticeDialog.dismiss();
                            } else {//生成

                                noticeDialog.dismiss();

                            }
                            noticeDialog.dismiss();

                        }
                    }, 4, "", "用户未登录，无权进行操作", "取消", "确定");
                    noticeDialog.show();
                }else{
                    readSQInfo(v);
                }

            }
        });


        setChangeLL(6);


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                sv_list.scrollTo(0,0);
            }
        }, 100);



        im_icon1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginUser user = BaseApp.getInstance().user;
                if(!"".equalsIgnoreCase(user.getUserName())) {
                    SetParaListActivity.start(getActivity());
                }else{
//                    AccountLoginActivity.start(getActivity());
                }
            }
        });



//        im_icon2.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//
//                LcndUtil.readFile(getActivity(),"2.dat");
//
//                LcndUtil.readAsserts(getActivity(),"2.dat");
//                LoginUser user = BaseApp.getInstance().user;
//                if(!"".equalsIgnoreCase(user.getUserName())) {
//
//                }else{
////                    AccountLoginActivity.start(getActivity());
//                }
//            }
//        });

        tv_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginUser user = BaseApp.getInstance().user;
                if("".equalsIgnoreCase(user.getUserName()))
                {
                    AccountLoginActivity.start(getActivity());
                }else{


                    noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String sendStatus = "";
                            if (view.getId() == R.id.btn_chancel_notice) {//暂存

                                noticeDialog.dismiss();
                            } else {//生成
                                BaseApp.getInstance().user.setUserName("");
                                BaseApp.getInstance().saveUser();
                                rePage();
                                noticeDialog.dismiss();

                            }
                            noticeDialog.dismiss();

                        }
                    }, 1, "", "确认注销用户？", "取消", "确定");
                    noticeDialog.show();
                }
            }
        });

//        EventBus.getDefault().register( this );
        initTimePicker();
        circleProgressDialog = new CircleProgressDialog(getActivity());
        circleProgressDialog.setText("命令执行中");

        return mView;
    }


    private void setChangeLL(int num )
    {

        ll_r_area1.setVisibility(View.GONE);
        ll_r_area2.setVisibility(View.GONE);
        ll_r_area3.setVisibility(View.GONE);
        ll_r_area4.setVisibility(View.GONE);
        ll_r_area5.setVisibility(View.GONE);
        ll_r_area6.setVisibility(View.GONE);


        ll_left1.setBackgroundColor(Color.parseColor("#F5F4F4"));
        ll_left2.setBackgroundColor(Color.parseColor("#F5F4F4"));;
        ll_left3.setBackgroundColor(Color.parseColor("#F5F4F4"));;
        ll_left4.setBackgroundColor(Color.parseColor("#F5F4F4"));;
        ll_left5.setBackgroundColor(Color.parseColor("#F5F4F4"));;
        ll_left6.setBackgroundColor(Color.parseColor("#F5F4F4"));;

        switch (num)
        {
            case 1:
                ll_left1.setBackgroundColor(Color.parseColor("#ffffff"));
                ll_r_area1.setVisibility(View.VISIBLE);
                break;
            case 2:
                ll_left2.setBackgroundColor(Color.parseColor("#ffffff"));
                ll_r_area2.setVisibility(View.VISIBLE);
                break;
            case 3:
                ll_left3.setBackgroundColor(Color.parseColor("#ffffff"));
                ll_r_area3.setVisibility(View.VISIBLE);
                break;
            case 4:
                ll_left4.setBackgroundColor(Color.parseColor("#ffffff"));
                ll_r_area4.setVisibility(View.VISIBLE);
                break;
            case 5:
                ll_left5.setBackgroundColor(Color.parseColor("#ffffff"));
                ll_r_area5.setVisibility(View.VISIBLE);
                break;
            case 6:
                ll_left6.setBackgroundColor(Color.parseColor("#ffffff"));
                ll_r_area6.setVisibility(View.VISIBLE);
                break;
        }
    }
    public void syncTime(View v)
    {
//        pvTime.show(v);
        SyncTimeActivity.start(getActivity());
    }
    private ShowSQInfoDialog noticeDialog1;

    public void readSQInfo(View v)
    {

        ReadMQActivity.start(getActivity());
//        String str = "";
//        if(Consts.isRealSQ) {
//            Dim2Data dimData = new Dim2Data(IDimFace.Dim_Two, 256);
//
//            DimXLib.StartScan(dimData);
//
//            if (dimData.GetDim2DataLen() > 0) {//获取到有效的扫码数据
//                byte[] data = dimData.GetDim2Data();//获取扫码数据
//
//                try {
//                    str = new String(data, "UTF-8");
//                } catch (Exception ex) {
//                    ex.printStackTrace();
//                }
//
//            }
//        }else {
//            String mstrRestartSend = "D6 C7 C4 DC C5 E4 B1 E4 D6 D5 B6 CB B1 EA D7 BC " +
//                    "D0 CD A3 AC C0 E0 D0 CD A3 BA 54 32 30 A3 AC B3 " +
//                    "A7 C9 CC A3 BA B3 A4 D4 B0 C9 EE C8 F0 BC CC B1 " +
//                    "A3 D7 D4 B6 AF BB AF D3 D0 CF DE B9 AB CB BE A3 " +
//                    "AC D0 CD BA C5 A3 BA 50 52 53 2D 33 33 38 31 A3 " +
//                    "AC 49 44 A3 BA 54 32 30 30 45 30 45 53 52 30 36 " +
//                    "30 32 30 31 39 31 32 32 34 30 32 30 31 A3 AC D3 " +
//                    "B2 BC FE B0 E6 B1 BE A3 BA 48 56 30 31 2E 30 30 " +
//                    "A3 AC C9 FA B2 FA C8 D5 C6 DA A3 BA 32 30 31 39 " +
//                    "C4 EA 31 32 D4 C2 32 34 C8 D5";
//            byte[] mRestart = null;
//            mRestart = HexCommandtoByte(mstrRestartSend.getBytes());
//            try {
//                str = new String(mRestart, "GB2312");
//            }catch ( Exception ex)
//            {
//                ex.printStackTrace();
//            }
//        }
//
//
//            noticeDialog1 = new ShowSQInfoDialog(getActivity(), new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    String sendStatus = "";
//                    if (view.getId() == R.id.tv_sm) {//暂存
//
////                        noticeDialog1.tv_sm.setVisibility(View.GONE);
//                        noticeDialog1.ll_content.setVisibility(View.VISIBLE);
//                    } else  {//生成
//
//                        noticeDialog1.dismiss();
//
//                    }
////                    noticeDialog1.dismiss();
//
//                }
//            }, 1, str, "确认注销用户？", "关闭", "确定");
//            noticeDialog1.show();
        }




    public void readSQInfo_bak(View v)
    {

        String str = "";
        if(Consts.isRealSQ) {
            Dim2Data dimData = new Dim2Data(IDimFace.Dim_Two, 256);

            DimXLib.StartScan(dimData);

            if (dimData.GetDim2DataLen() > 0) {//获取到有效的扫码数据
                byte[] data = dimData.GetDim2Data();//获取扫码数据

                try {
                    str = new String(data, "UTF-8");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }
        }else {
          String mstrRestartSend = "D6 C7 C4 DC C5 E4 B1 E4 D6 D5 B6 CB B1 EA D7 BC " +
                  "D0 CD A3 AC C0 E0 D0 CD A3 BA 54 32 30 A3 AC B3 " +
                  "A7 C9 CC A3 BA B3 A4 D4 B0 C9 EE C8 F0 BC CC B1 " +
                  "A3 D7 D4 B6 AF BB AF D3 D0 CF DE B9 AB CB BE A3 " +
                  "AC D0 CD BA C5 A3 BA 50 52 53 2D 33 33 38 31 A3 " +
                  "AC 49 44 A3 BA 54 32 30 30 45 30 45 53 52 30 36 " +
                  "30 32 30 31 39 31 32 32 34 30 32 30 31 A3 AC D3 " +
                  "B2 BC FE B0 E6 B1 BE A3 BA 48 56 30 31 2E 30 30 " +
                  "A3 AC C9 FA B2 FA C8 D5 C6 DA A3 BA 32 30 31 39 " +
                  "C4 EA 31 32 D4 C2 32 34 C8 D5";
             byte[] mRestart = null;
            mRestart = HexCommandtoByte(mstrRestartSend.getBytes());
            try {
                str = new String(mRestart, "GB2312");
            }catch ( Exception ex)
            {
                ex.printStackTrace();
            }
        }
        if(!"".equalsIgnoreCase(str)) {

            noticeDialog1 = new ShowSQInfoDialog(getActivity(), new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String sendStatus = "";
                    if (view.getId() == R.id.btn_chancel_notice) {//暂存

                        noticeDialog1.dismiss();
                    } else {//生成

                        noticeDialog1.dismiss();

                    }
                    noticeDialog1.dismiss();

                }
            }, 1, str, "确认注销用户？", "关闭", "确定");
            noticeDialog1.show();
        }


    }

    public static byte[] HexCommandtoByte(byte[] data) {
        if (data == null) {
            return null;
        }
        int nLength = data.length;

        String strTemString = new String(data, 0, nLength);
        String[] strings = strTemString.split(" ");
        nLength = strings.length;
        data = new byte[nLength];
        for (int i = 0; i < nLength; i++) {
            if (strings[i].length() != 2) {
                data[i] = 00;
                continue;
            }
            try {
                data[i] = (byte)Integer.parseInt(strings[i], 16);
            } catch (Exception e) {
                data[i] = 00;
                continue;
            }
        }

        return data;
    }
    @Override
    public  void onDestroy() {
        super.onDestroy();
        BaseApp.getInstance().user.setUserName("");
        BaseApp.getInstance().saveUser();
//        EventBus.getDefault().unregister( this );
    }

    private PublicNoticeDialog noticeDialog;
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


    }


    @Subscribe
    public void onEvent(final retData result) {
        //接收以及处理数据
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                int strType = result.getType();
                int ret = result.getRet();
                int status = result.getStatus();

//                if(strType == Consts.cm_systime)
//                {
//                    circleProgressDialog.dismiss();
//                    if(ret == Consts.cm_timeout) {
//                        TopToastUtil.getInstance(getActivity(), R.layout.showdialog).showShortToast("命令执行超时");
//                    }
//
//                    if(ret == Consts.cm_end) {
//                        if(status == 1) {
//                            TopToastUtil.getInstance(getActivity(), R.layout.showdialog).showShortToast("时间同步执行成功");
//                        }else{
//                            TopToastUtil.getInstance(getActivity(), R.layout.showdialog).showShortToast("时间同步执行失败");
//
//                        }
//                    }
//                }

            }
        });




    };


    @Override
    public void onResume() {
        super.onResume();
        rePage();
    }

    private void rePage()
    {
        LoginUser user = BaseApp.getInstance().user;
        if("".equalsIgnoreCase(user.getUserName()))
        {
            tv_name.setText("");
            im_icon1.setImageResource(R.drawable.im_icon1_u);
            im_icon2.setImageResource(R.drawable.im_icon2_u);
            im_icon4.setImageResource(R.drawable.im_icon4_u);
            tv_login.setText("用户登录");
        }else{
            im_icon1.setImageResource(R.drawable.im_icon1);
            im_icon2.setImageResource(R.drawable.im_icon2);
            im_icon4.setImageResource(R.drawable.im_icon4);
            tv_login.setText("退出登录");
            tv_name.setText("登录用户:"+user.getUserName());
        }
        topAppAdapter.notifyDataSetChanged();
    }


    @Override
    public void onClick(View v) {

    }

    public void show()
    {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(getActivity(), perms)) {
            showFileChooser();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "申请权限",
                    10001, perms);
        }
    }
    private PagingItemDecoration pagingItemDecoration = null;
    private HorizontalPageLayoutManager horizontalPageLayoutManager = null;
    public void initIconNew(View mView)
    {

        horizontalPageLayoutManager = new HorizontalPageLayoutManager(2, 4);
        pagingItemDecoration = new PagingItemDecoration(getActivity(), horizontalPageLayoutManager);

        recyclerView = (RecyclerView) mView.findViewById(R.id.recyclerview);
        ArrayList topAppData = new ArrayList<TopRK>();

        topAppAdapter = new AppAdapter(getActivity(),topAppData,this);
        recyclerView.setAdapter(topAppAdapter);
        scrollHelper.setUpRecycleView(recyclerView);
        scrollHelper.setOnPageChangeListener(this);
        recyclerView.setHorizontalScrollBarEnabled(true);
        RecyclerView.LayoutManager layoutManager = null;
        RecyclerView.ItemDecoration itemDecoration = null;

        layoutManager = horizontalPageLayoutManager;
//        itemDecoration = pagingItemDecoration;

        if (layoutManager != null) {
            recyclerView.setLayoutManager(layoutManager);
//            recyclerView.removeItemDecoration(lastItemDecoration);
//            recyclerView.addItemDecoration(itemDecoration);
            scrollHelper.updateLayoutManger();
            scrollHelper.scrollToPosition(0);

//            lastItemDecoration = itemDecoration;
        }

//        TopRK top1 = new TopRK();
//        top1.setTitle(Consts.toprk1);
//        topAppData.add(top1);

        TopRK top2 = new TopRK();
        top2.setTitle(Consts.toprk2);
        topAppData.add(top2);

        TopRK top7 = new TopRK();
        top7.setTitle(Consts.toprk7);
        topAppData.add(top7);

        TopRK top3 = new TopRK();
        top3.setTitle(Consts.toprk3);
        topAppData.add(top3);

        TopRK top4 = new TopRK();
        top4.setTitle(Consts.toprk4);
        topAppData.add(top4);

        TopRK top5 = new TopRK();
        top5.setTitle(Consts.toprk5);
        topAppData.add(top5);

        TopRK top6 = new TopRK();
        top6.setTitle(Consts.toprk6);
        topAppData.add(top6);



        TopRK top8 = new TopRK();
        top8.setTitle(Consts.toprk8);
        topAppData.add(top8);

        TopRK top9 = new TopRK();
        top9.setTitle(Consts.toprk9);
        topAppData.add(top9);

//        TopRK top10 = new TopRK();
//        top10.setTitle(Consts.toprk10);
//        topAppData.add(top10);
//
//        TopRK top11 = new TopRK();
//        top11.setTitle(Consts.toprk11);
//        topAppData.add(top11);

//        TopRK top12 = new TopRK();
//        top12.setTitle(Consts.toprk12);
//        topAppData.add(top12);

//        topAppAdapter.updateData(topAppData);





//        updateData();
    }

    @Override
    public void onPageChange(int index) {

    }


    private static final int FILE_SELECT_CODE = 0;
    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(getActivity(), "Please install a File Manager.", Toast.LENGTH_SHORT).show();
        }
    }

    private static final String TAG = "ChooseFile";
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    // Get the Uri of the selected file
                    Uri uri = data.getData();
                    Log.d(TAG, "==File Uri: " + uri.toString());
                    // Get the path
                    try {
                        String path = getPath(getActivity(), uri);
                        Log.d(TAG, "==File Path: " + path);
//                        int ret =  setApi.getInstance(this).updateVer(path);
//                        setCmdRet(ret,"app更新");
                        TopToastUtil.getInstance(getActivity(),R.layout.showdialog).showShortToast("升级成功");
                    }catch (Exception ex)
                    {
                        ex.printStackTrace();
                    }
                    // Get the file instance
                    // File file = new File(path);
                    // Initiate the upload
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public static String getPath(final Context context,final Uri uri) throws URISyntaxException {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }



    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    private void initTimePicker() {//Dialog 模式下，在底部弹出
        pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
//                Toast.makeText(context, getTime(date), Toast.LENGTH_SHORT).show();
                Log.i("pvTime", "onTimeSelect");
//                TopToastUtil.getInstance(getActivity(),R.layout.showdialog).showShortToast("时间同步成功");
                int ret =  setApi.getInstance(getActivity()).sysTime(new Date());
                if(ret ==1)
                {
                    circleProgressDialog.showDialog();
                }else{
                    TopToastUtil.getInstance(getActivity(),R.layout.showdialog).showShortToast("发送时间同步失败");

                }
            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {
                        Log.i("pvTime", "onTimeSelectChanged");

                    }
                })
                .setTitleText("查询设置")
                .setType(new boolean[]{true, true, true, true, true, true})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("pvTime", "onCancelClickListener");
                    }
                })
                .setItemVisibleCount(5) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }


}
